<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>快速排序</title>
</head>

<body>
  <script>
    /* 
     * quick: 实现快速排序
     *  @params
     *    ary [array] 需要排序的数组
     *  @return
     *    [array] 排序后的新数组
     * by chenjing on 2021/01/23
    */
    function quick(ary) {
      if(ary.length <= 1) {
        return ary;
      }
      let middleIndex = Math.floor(ary.length / 2);
      let middleValue = ary.splice(middleIndex, 1)[0];
      let aryLeft = [],
          aryRight = [];
      for(let i = 0; i < ary.length; i++) {
        let item = ary[i];
        item < middleValue ? aryLeft.push(item) : aryRight.push(item);
      }
      return quick(aryLeft).concat(middleValue, quick(aryRight));
    }
    let ary = [12, 8, 15, 16, 1, 24];
    let result = quick(ary);
    console.log(result);

    // 递归: 函数执行的时候自己调用自己
   /*  function fn() {
      // 递归
      // fn(); // Uncaught RangeError: Maximum call stack size exceeded 这种死递归会导致栈溢出
      setTimeout(fn, 0); // 这种看似像递归的方法不会导致栈溢出错误

    }
    fn(); */

    // 获取1-10的和
    /* let total = null;
    for(let i = 1; i <= 10; i++) {
      total += i;
    }
    console.log(total); */

    /* function sum(n) {
      if(n > 10) {
        return 0;
      }
      return n + sum(n + 1);
    }
    let total = sum(1);
    console.log(total); */
  </script>
</body>

</html>